package com.hgw.ordinary.service.impl;

import com.hgw.ordinary.common.FileResult;
import com.hgw.ordinary.service.UploadDownloadService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Description: 基于服务器的文件上传与下载
 * @date 2022/10/4 11:08
 * @author itLaboratory-YanAn
 */
@Service
public class UploadDownloadServiceImpl implements UploadDownloadService {

    @Value("${file.path}")
    private String basePath;

    @Value("${file.rootPath}")
    private String rootPath;

    @Value("${file.staticPatternPath}")
    private String staticPatternPath;

    @Override
    public FileResult upload(MultipartFile multipartFile, String dir) {
        FileResult fileResult = new FileResult();
        try {
            // 1. 拼接功能子文件夹
            String completePath = basePath + dir + "/";

            // 2. 拼接日期目录
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
            String dataPath = dateFormat.format(new Date());
            completePath = completePath + dataPath + "/";

            // 指定文件上传的目录(基本路径+功能子文件夹+日期路径)，若不存在目录则创建
            File targetFile = new File(completePath);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }

            // 3. 使用 UUID 重新生成文件名，防止文件名重复造成文件覆盖
            String originalFilename = multipartFile.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString() + suffix;

            // 4. 文件上传到指定的目录
            multipartFile.transferTo(new File(completePath + fileName));

            // 5. 封装处理信息
            fileResult.setSuccess(true);
            fileResult.setUrl(rootPath + "/" + staticPatternPath + "/" + dir + "/" + dataPath + "/" + fileName);
            fileResult.setPath(dir + "/" + dataPath + "/" + fileName);
            fileResult.setSize(multipartFile.getSize());
            fileResult.setFileName(fileName);
            fileResult.setExt(suffix);
        } catch (IOException e) {
            e.printStackTrace();
            fileResult.setSuccess(false);
        }
        return fileResult;
    }
}
